﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using weikebuluo.DBUtility;
using weikebuluo.Controllers.Cs.Customer;
using NVelocity.Context;
using NVelocity;
using weikebuluo.Common;

namespace weikebuluo.web.Customer.Ashx
{
    /// <summary>
    /// List 的摘要说明
    /// </summary>
    public class List : IHttpHandler
    {
        JsonOperate JsonOperate = new JsonOperate();

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            int _mid = 0;   //企业Id
            int _cid = 0;   //分类Id
            int.TryParse(context.Request.QueryString["userid"], out _mid);
            int.TryParse(context.Request.QueryString["cid"], out _cid);

            string _area = context.Request.QueryString["area"];          //地区
            string _industry = context.Request.QueryString["industry"];  //分类
            string _status = context.Request.QueryString["status"];      //
            string time = DateTime.Now.ToString();

            int page = 0;
            int _p = 0;
            _p = int.TryParse(context.Request.QueryString["p"], out _p) ? _p : 1;
            _p = int.TryParse(context.Request.Form["page"], out page) ? page : _p;
            int _rows = 10; //每页显示行数
            int _start = (_p - 1) * _rows + 1;//本页首行记录
            int _end = _p * _rows;//本页首行记录

            if (_mid != 0 && _cid != 0)
            {
                SqlParameter[] para = new SqlParameter[] { 
                    new SqlParameter("@mid",_mid),
                    new SqlParameter("@cid",_cid),
                    new SqlParameter("@start",_start),
                    new SqlParameter("@end",_end)
                };

                string sqlWhere = "";

                if (!string.IsNullOrEmpty(_area))
                {
                    _area = context.Server.UrlDecode(_area);

                    if (_area.IndexOf("全部") == -1)
                    {
                        sqlWhere += " and NArea='" + _area + "'";
                    }
                    else
                    {
                        _area = "全部地区";
                    }
                }
                else
                {
                    _area = "全部地区";
                }

                if (!string.IsNullOrEmpty(_industry))
                {
                    _industry = context.Server.UrlDecode(_industry);

                    if (_industry.IndexOf("全部") == -1)
                    {
                        sqlWhere += " and NIndustryName='" + _industry + "'";
                    }
                    else
                    {
                        _industry = "全部分类";
                    }
                }
                else
                {
                    _industry = "全部分类";
                }

                if (!string.IsNullOrEmpty(_status))
                {
                    if (_status == "1")
                    {
                        sqlWhere += " and (NStartDate>'" + time + "' or NEndDate<'" + time + "')";
                    }
                    else if (_status == "2")
                    {
                        sqlWhere += " and (NStartDate<='" + time + "' and NEndDate>='" + time + "')";
                    }
                    else
                    {
                        _status = "0";
                    }
                }
                else
                {
                    _status = "0";
                }

                if (page == 0)
                {
                    DataTable dtMerchant = DbHelperSQL.Query("Select MId,[MName],[CopyRight],[Template],user_id,Description,MPhone,KeyWords,HomeShareImg from t_set_view where user_id=@mid", para).Tables[0];

                    if (dtMerchant.Rows.Count > 0)
                    {
                        DataRow drMerchant = dtMerchant.Rows[0];

                        DataTable dtCategory = DbHelperSQL.Query("select * from t_newscate where Cid=@cid and user_id=@mid", para).Tables[0];

                        if (dtCategory.Rows.Count == 1)
                        {
                            DataRow drCategory = dtCategory.Rows[0];

                            DataSet ds = DbHelperSQL.Query(@"select NId,NTitle,NPicUrl,NContentType,NContent,NStatus From t_news where user_id=@mid and Cid=@cid and NStatus=1 and Stick=1 order by NSort,NCreateDate desc; 
                                                       select * from (select NId,NTitle,NSPicUrl,NContentType,NContent,Description,Convert(varchar(10),NCreateDate,121) NCreateDate,NStartDate,NEndDate,NIndustryType,NIndustryName,NProvince,NCity,NArea,Row_number() over(order by NSort,NCreateDate desc) RID From t_news where NStatus=1 and user_id=@mid and Cid=@cid" + sqlWhere + @") A where RID between @start and @end; 
                                                       select count(1) from t_news where NStatus=1 and user_id=@mid and Cid=@cid" + sqlWhere + @";
                                                      
                                                       select distinct NArea from t_news where NStatus=1 and user_id=@mid and Cid=@cid and NArea is not null;
                                                       select distinct NIndustryName from t_news where NStatus=1 and user_id=@mid and Cid=@cid and NIndustryName is not null;
                                                       select Id,Name,PicUrl,Href,Type,BgColor,Opacity,Color,BgImg,Name_Status,PicUrl_Status,BgImg_Status From t_icon where user_id=@mid and Status=1 order by case when sort is null then 1 else 0 end,sort;", para);

                            DataTable dtStick = ds.Tables[0];
                            DataTable dtNews = ds.Tables[1];
                            DataTable dtArea = ds.Tables[3];
                            DataTable dtIndustry = ds.Tables[4];
                            DataTable dtHomeIcon = ds.Tables[5];

                            int count = Convert.ToInt32(ds.Tables[2].Rows[0][0]);
                            int _previous = _p - 1;   //上一页
                            int _next = _p + 1;   //下一页

                            //列表样式
                            string _listCss = "/web/wechat/website/" + (string.IsNullOrEmpty(drMerchant["Template"].ToString()) ? "Default" : drMerchant["Template"].ToString()) + "/Css/List.css"; //文章列表Css
                           

                            //菜单样式
                            string _menuCss = "/web/wechat/website/" + (string.IsNullOrEmpty(drMerchant["Template"].ToString()) ? "Default" : drMerchant["Template"].ToString()) + "/Css/Menu.css";
                            

                            //设置参数
                            IContext template = new VelocityContext();
                            template.Put("merchant", drMerchant);
                            template.Put("stick", dtStick);
                            template.Put("news", dtNews);
                            template.Put("dtarea", dtArea);
                            template.Put("dtindustry", dtIndustry);
                            template.Put("currentPage", _p);
                            template.Put("totalPage", Math.Ceiling(count / (_rows * 1.0)));
                            template.Put("category", drCategory);
                            template.Put("previous", _previous);
                            template.Put("next", _next);
                            template.Put("listcss", _listCss);
                            template.Put("menucss", _menuCss);
                            template.Put("area", _area);
                            template.Put("industry", _industry);
                            template.Put("status", _status);
                            template.Put("time", time);
                            template.Put("icon", dtHomeIcon);//图标按钮

                            BaseTemp bt = new BaseTemp();
                            context.Response.Write(bt.WriterTemplate("/web/wechat/website/" + (string.IsNullOrEmpty(drMerchant["Template"].ToString()) ? "Defualt" : drMerchant["Template"].ToString()) + "/List.html", template, 0));
                        }
                        else
                        {
                            context.Response.Write("参数不正确");
                        }
                    }
                    else
                    {
                        context.Response.Write("参数不正确");
                    }
                }
                else
                {
                    DataSet ds = DbHelperSQL.Query(@"select * from (select NId,NTitle,NSPicUrl,NContentType,NContent,Description,Convert(varchar(10),NCreateDate,121) NCreateDate,NStartDate,NEndDate,NIndustryType,NIndustryName,NProvince,NCity,NArea,Row_number() over(order by NSort,NCreateDate desc) RID From t_news where NStatus=1 and user_id=@mid and Cid=@cid" + sqlWhere + @") A where RID between @start and @end;
                                                     select count(1) from t_news where NStatus=1 and user_id=@mid and Cid=@cid" + sqlWhere + @";", para);
                    context.Response.Write("{\"pagecount\":\"" + ds.Tables[1].Rows[0][0] + "\",\"items\":" + JsonOperate.TableToBasicJson(ds.Tables[0]) + "}");
                }
            }
            else
            {
                context.Response.Write("参数不正确");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}